﻿using Microsoft.AspNetCore.Mvc;
using GoodDotNet.Service;
using Microsoft.AspNetCore.Authorization;
using GoodDotNet.Core.Model;
using GoodDotNet.WebAdmin.HttpContextUser;
using Microsoft.Extensions.Options;
using GoodDotNet.Core.Data;
using NetCoreClass;
using System.Net;
using System.Net.Http.Headers;
using GoodDotNet.Core.Entity;
using GoodDotNet.Core.Model.Params;
using GoodDotNet.WebAdmin.AuthHelper.Policys;

namespace GoodDotNet.WebAdmin.Controllers
{
	[ApiController]
	[Route("api/[controller]")]
	public class AdminUserController : BaseController
	{
		private Audiences _audiences;
		private IWebHostEnvironment _webHostEnvironment;
        public AdminUserController(IUser user, IHttpContextAccessor accessor, IOptions<List<ConnectionString>> conns, ILogger<BaseController> logger, IOptions<Appsettings> appsettings,IOptions<Audiences>audience,IWebHostEnvironment webHostEnvironment) : base(user, accessor, conns, logger, appsettings)
        {
			this._audiences = audience.Value;
			this._webHostEnvironment = webHostEnvironment;
        }

        [HttpPost]
		[Route("Add")]
		[AllowAnonymous]
		public Result Add([FromBody] ParInsertAdminUserModel pars)
		{

			using (var uniOfWork = new UnitOfWork(_conStr))
			{
				AdminUserService service = new AdminUserService(uniOfWork);
				return service.Add(pars, _context, _appsettings.access_token);
			}
		}

		[HttpPost]
		[Route("reset-pwd")]
		public Result ResetPwd([FromBody] AdminUserInitParModel pars)
		{
			using (var uniOfWork = new UnitOfWork(_conStr))
			{
				AdminUserService service = new AdminUserService(uniOfWork);
				var obj = service.ResetPwd(pars,_appsettings.access_token,_webHostEnvironment.ContentRootPath);
				return obj;
			}

		}

		/// <summary>
		/// 登录
		/// </summary>
		/// <param name="pars"></param>
		/// <returns></returns>
		[HttpPost]
		[Route("login")]
		public Result Login([FromBody] LoginParams pars)
		{
			object result = null;
			var codeStr = _context.Session.GetString(_appsettings.ApiName);

#if DEBUG

#else
			if (!String.Equals(pars.captcha, codeStr, StringComparison.CurrentCultureIgnoreCase))
            {
				return Error("验证码错误");
            }
#endif
			int yzcode = 0;
			if (_context.Session.GetInt32("yzcode") != null)
			{
				yzcode = (int)_context.Session.GetInt32("yzcode");
				if (yzcode > 5)
				{
					return Error("密码错误次数太多，禁止登陆！");
				
				}
			}
			using (var uniOfWork = new UnitOfWork(_conStr))
			{
				DESEncryptor des = new DESEncryptor();
				string pwd = des.md5Salt(pars.password, _appsettings.access_token);
				var data = uniOfWork.AdminUserRepository.Get(a => a.UserName == pars.username);
				if (data == null)
				{
					return Error("没有这个用户");
					
				}
				if (!pwd.Equals(data.Pwd))
				{
					return Error("密码错误");
				}
				if (data.IsQuit)
				{
					return Error("您已经离职不能登录了");
				
				}
				var response =new JwtToken(_audiences).BuildJwtToken(data.UserName, data.Id.ToString(),"");
				_context.Session.Remove("yzcode");
				return Sucess(response);
	
			}


		}

		[HttpPost]
		[Route("GetOne")]
		[Authorize]
		public Result GetOne([FromBody] PostID pars)
		{

			using (var uniOfWork = new UnitOfWork(_conStr))
			{
				AdminUserService service = new AdminUserService(uniOfWork);
				var obj = service.GetOne(pars.ID);
				return Sucess(obj);
			}


		}

		[HttpPost]
		[Route("GetPage")]
		[Authorize]
		public Result GetPage([FromBody] ParGetpageAdminUserModel pars)
		{

			using (var uniOfWork = new UnitOfWork(_conStr))
			{
				AdminUserService service = new AdminUserService(uniOfWork);
				var obj = service.GetPage(pars);
				return Sucess(obj);
			}



		}
		[HttpPost]
		[Route("info")]
		[Authorize]
		public Result info()
		{

			using (var uniOfWork = new UnitOfWork(_conStr))
			{
				AdminUserService service = new AdminUserService(uniOfWork);
				var obj = service.info(_user.Id);
				return Sucess(obj);
			}


		}

		[HttpPost]
		[Route("Delete")]
		[Authorize]
		public Result Delete([FromBody] PostID pars)
		{

			using (var uniOfWork = new UnitOfWork(_conStr))
			{
				AdminUser entity = uniOfWork.AdminUserRepository.Get(a => a.Id == pars.ID);
				if (entity == null)
				{
					return Error("找不到记录");
				}
				uniOfWork.AdminUserRepository.Remove(entity);
				uniOfWork.SaveChanges();
				return Sucess("sucess");
			}

		}

		[HttpPost]
		[Route("Update")]
		[Authorize]
		public Result Update([FromBody] ParUpdateAdminUserModel pars)
		{

			using (var uniOfWork = new UnitOfWork(_conStr))
			{
				AdminUserService service = new AdminUserService(uniOfWork);
				if (pars.id == null)
				{
					pars.id = _user.Id;
				}
				service.Update(pars);
			}
			return Sucess("sucess");


		}




		[HttpPost]
		[Route("EditPwd")]
		[Authorize]
		public Result EditPwd([FromBody] ParUpdateEditPwdAdminuserModel pars)
		{

			using (var uniOfWork = new UnitOfWork(_conStr))
			{
				AdminUserService service = new AdminUserService(uniOfWork);
				return service.EditPwd(pars, _user.Id,_appsettings.access_token);
			}

		}

		/// <summary>
		/// 获取验证码
		/// </summary>
		[AllowAnonymous]
		[HttpGet]
		[Route("ValidateCode")]
		public IActionResult ValidateCode()
		{
			HttpResponseMessage resp = new HttpResponseMessage(HttpStatusCode.OK);
			CaptchaImage captcha = new CaptchaImage(200, 60);
			string chkCode = captcha.CreateValidateCode(4);
			_context.Session.SetString(_appsettings.ApiName, chkCode);
			var bytes = captcha.CreateByteByImgVerifyCode();

			var response = new HttpResponseMessage(HttpStatusCode.OK);
			response.Content = new ByteArrayContent(bytes);
			response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
			response.Headers.CacheControl = new CacheControlHeaderValue()
			{
				NoCache = true,
				MaxAge = TimeSpan.Zero
			};
			return new FileContentResult(bytes, "image/png");
		}

		/// <summary>
		/// 用户菜单
		/// </summary>
		/// <returns></returns>
		[HttpPost]
		[Authorize]
		[Route("menu-router")]
		public Result menuRouter()
		{
		
			using (var unitOfWork = new UnitOfWork(_conStr))
			{
				var service = new AdminUserService(unitOfWork);
				return  service.menuRouter(_user.Id);
			}
		
		}
		[HttpPost]
		[AllowAnonymous]
		[Route("RefreshToken")]
		public Result RefreshToken()
		{
			var jwtToken = new JwtToken(_audiences);
			int? uid =jwtToken.ReadToken(_context);
			if (uid == null)
			{
				return Error("超期了，请重新登录");
			}
			else
			{
				using (var uniOfWork = new UnitOfWork(_conStr))
				{
					var user = uniOfWork.AdminUserRepository!.Get(u => u.Id == uid);
					if (user != null)
					{
						var response = jwtToken.BuildJwtToken(user.UserName!,user.Id.ToString(),"");
						return Sucess(response);
					}
					else
					{
						return Error("找不到这个用户");
					}
				}
			}
		
		}
		/// <summary>
		/// 注销账户信息
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		[Authorize]
		[HttpPost]
		[Route("LoginOut")]
		public Result LoginOut()
		{

			return Sucess("注销成功");
		}
	}
}
